package com.handsoninfo;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.sourceforge.tess4j.ITessAPI;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.Word;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class Recognition {

    final Tesseract instance;
    public Recognition() {
        instance = new Tesseract();
        instance.setLanguage("chi_sim");
    }

    @Getter
    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    public static class Instance {

        final BufferedImage bi;

        final List<Word> words;

        final Division divisions;

    }
    public Instance recognize(File image) {
        try {

            final BufferedImage bi;

            final List<Word> words;

            final Division divisions;

            bi = ImageIO.read(image);

            words = instance.getWords(bi, ITessAPI.TessPageIteratorLevel.RIL_WORD);
            List<Word> blocks = instance.getWords(bi, ITessAPI.TessPageIteratorLevel.RIL_TEXTLINE);

            divisions = new Division(blocks);
            for (Word word : words) {
                Rectangle rect = word.getBoundingBox();
                if (rect.x > bi.getWidth() || rect.y > bi.getHeight()) continue;
                if (word.getBoundingBox().x > bi.getWidth() * 0.9) continue;
                divisions.putWord(Utils.isBlue(bi, word), word);
            }

//            Division.Normalized normalizedDivisions = divisions.normalize();
//
//            System.out.println(normalizedDivisions.getAddress());
//            System.out.println(normalizedDivisions.getNum());

            return new Instance(bi, words, divisions);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
